package com.xp.gather2.client;

import com.xp.gather2.config.ClientConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Data
@Slf4j
@Component
public class LampClient {
    private Channel channel = getchannel();

    private LampHandler firstClientHandler;
    @Autowired
    public LampClient(LampHandler firstClientHandler) {
        this.firstClientHandler=firstClientHandler;
    }

    /**
     *
     * @return :Channer
     */
    private Channel getchannel() {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(10240));
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(firstClientHandler);
                    }
                });
        return bootstrap.connect(ClientConfig.SERVERIP, ClientConfig.SERVERPORT).channel();
    }


    public Channel getChannel() {
        if (!LampHandler.ISCONNECT) {
            this.channel=getchannel();
        }
        return channel;
    }
}
